const invoiceRules = {
    company: [{
		required: true,
		message: '  ',
		trigger: 'blur'
	}],
	duty_paragraph: [{
		required: true,
		message: ' ',
		trigger: 'blur'
	}]
};

let app = new Vue({
    el: "#app",
    data() {

        return {

        	leftbar_show:true,
			tableHeight:window.innerHeight- 180,

            //在职员工列表
            users:[],

            //展开行的数组
            expands: [],
            getRowKeys(row) {
                return row.id
            },
            //时间查询
            pickerOptions: {
			  shortcuts: [{
				text: '最近一周',
				onClick(picker) {
				  const end = new Date()
				  const start = new Date()
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
				  picker.$emit('pick', [start, end])
				}
			  }, {
				text: '最近一个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
				  picker.$emit('pick', [start, end]);
				}
			  }, {
				text: '最近三个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
				  picker.$emit('pick', [start, end]);
				}
			  }]
			},
            //子表
			tablecolums:[],
			//主表
			tableData:[],
			invoiceTypes:["专票","电子专票","普票","电子普票"],
			queryForm:{
                keyword: '',//关键字
				remake:'',//托管
				invoice_seal:'',//发票章
				policeNumber:'',//发票最低提醒数量
				status:'',
				billing_time:'',

				pageNo:1, // 当前页码
				pagesize:100 ,// 每页记录数
				pagesizes:[10,20,50,100,500]
			},
			pagetotal:0,

            //发票新增
			dialogFormVisible : false,
			insertcompany:{
			    company: '',//公司
			    customer_id:'',
				remake:'',//托管(联动)
				invoice_seal:'公司保管',//发票章
				remarks:'',
				duty_paragraph:'',//税号
				spaecialticket_number:'',
				spaecialticket_quota:'',
				electronicspaecialticket_number:'',
				electronicspaecialticket_quota:'',
				generalticket_number:'',
				generalticket_quota:'',
				electronicgeneralticket_number:'',
				electronicgeneralticket_quota:''
			},
			//tran_agentKeeping表公司名列表
			companys:[],

            //公司发票编辑
            dialogEditClick : false,
            updatecompany : {
                "invoiceId":'',
                "compname":"",
			    "remake":"",
			    "invoice_seal":"",
			    "remarks":"",
                "spaecialticket_number":"",
                "spaecialticket_quota":"",
                "spaecialticket_is":"",
                "electronicspaecialticket_number":"",
			    "electronicspaecialticket_quota":'',
			    "electronicspaecialticket_is":'',
			    "generalticket_number":'',
			    "generalticket_quota":'',
			    "generalticket_is":'',
			    "electronicgeneralticket_number":'',
			    "electronicgeneralticket_quota":'',
			    "electronicgeneralticket_is":'',
			    "status":'',
			    "taxtype":''
            },

            //增票
            dialogInsertClick : false,
            insertclick : {
                "invoicecompany_id":'',//公司id
                "compname":'',//公司名称
                "billingType":'',//发票类型
                "billingTime":'',//开票时间
                "number":'',//增票数量
                "billingPerson":'',//增票人
                "userId": Number(localStorage.getItem('USERID'))
            },

            //减票
            dialogDeleteClick: false,
            deleteclick : {
                "invoicecompany_id":'',//公司id
                "compname":'',//公司名称
                "billingType":'',//发票类型
                "billingTime":'',//开票时间
                "number":'',//开票数量

                "billingPerson":'',//减票人
                "userId": Number(localStorage.getItem('USERID'))
            },

            //文件上传
            dialogImageUrl: '',
            dialog : false,

			// 上传原件统计表
            headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
            // 导入对话框
			dialogimportFormVisible:false,
			uploadurl:axios.defaults.baseURL + "api/invoicefunction/import",

        }
    },
	methods: {

        // 显示侧边栏
		showLeftBar() {
			if (this.leftbar_show) {
				this.leftbar_show = false
			} else {
				this.leftbar_show = true
			}
		},

        //获取可以新增公司信息
		async getCompanys() {
		    // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

			try {
				// 去搜索该公司的发票详细信息
                let res = await axios.post('api/invoicefunction/getCompanys');
                if (res.code === 200) {
                    this.companys = res.data;
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('查询公司名称请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},

        //点击选中建议项时触发
        handleSelect(item) {
            this.insertcompany = {
			    company: item.value,//公司
			    customer_id:item.customer_id,
				remake:item.remake,//托管
				invoice_seal:'公司保管',//发票章
				remarks:'',
				duty_paragraph:'',//税号
				spaecialticket_number:'0',
				spaecialticket_quota:'0',
				electronicspaecialticket_number:'0',
				electronicspaecialticket_quota:'0',
				generalticket_number:'0',
				generalticket_quota:'0',
				electronicgeneralticket_number:'0',
				electronicgeneralticket_quota:'0'
			};
			this.updatecompany.customer_id = item.customer_id;
			this.updatecompany.remake = item.remake;
        },

        //输入后匹配输入建议
        querySearch(queryString, cb) {
            var restaurants = this.companys;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },

        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },

        insertCompanyClick() {
            this.dialogFormVisible = true;
            this.insertcompany = {
			    company: '',//公司
			    customer_id:'',
				remake:'',//托管
				invoice_seal:'公司保管',//发票章
				remarks:'',
				duty_paragraph:'',//税号
				spaecialticket_number:'0',
				spaecialticket_quota:'0',
				electronicspaecialticket_number:'0',
				electronicspaecialticket_quota:'0',
				generalticket_number:'0',
				generalticket_quota:'0',
				electronicgeneralticket_number:'0',
				electronicgeneralticket_quota:'0'
			};
        },

        //新增提交
        async insertCompany() {

            if (this.insertcompany.company == '' || this.insertcompany.remake == '' || this.insertcompany.invoice_seal == '' || this.insertcompany.duty_paragraph == ''
                || this.insertcompany.spaecialticket_quota == '' || this.insertcompany.electronicspaecialticket_quota == '' || this.insertcompany.duty_paragraph == '' ||
                this.insertcompany.generalticket_quota == '' || this.insertcompany.electronicgeneralticket_quota == '' || this.insertcompany.spaecialticket_number == '' ||
                this.insertcompany.electronicspaecialticket_number == '' || this.insertcompany.generalticket_number == ''
                || this.insertcompany.electronicgeneralticket_number == '') {
                this.$message({
                    message: '表单项除了备注不能有空',
                    type: 'warning'
                });
                return
            }

            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

            //后台增加数据，如果没有这个公司信息，则增加此公司信息；如果有，那么增加该公司此种发票信息
			try {
				// 去搜索该公司的发票详细信息
                let res = await axios.post('api/invoicefunction/insertCompany', {"queryForm" : this.queryForm, "insertcompany" : this.insertcompany});
                if (res.code === 200) {
                    this.tableData = res.data.data;
                    this.pagetotal = res.data.total;
                    this.companys = res.data.companys;
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('公司发票添加出错！', e.message);
			}
			// 关闭加载框
			loading.close();

            this.dialogFormVisible = false;
            //清空
            this.insertcompany = {
			    company: '',//公司
			    customer_id:'',
				remake:'',//托管(联动)
				invoice_seal:'公司保管',//发票章(联动)
				remarks:'',
				duty_paragraph:'',//税号
				spaecialticket_number:'0',
				spaecialticket_quota:'0',
				electronicspaecialticket_number:'0',
				electronicspaecialticket_quota:'0',
				generalticket_number:'0',
				generalticket_quota:'0',
				electronicgeneralticket_number:'0',
				electronicgeneralticket_quota:'0'
			};
        },

        //新增提交取消
        cancelInsert() {
            this.dialogFormVisible = false;
        },

        //作废确认框
        async updatestate(row) {
            this.$confirm('此操作将永久作废, 是否继续?', '提示', {
              confirmButtonText: '确 定',
              cancelButtonText: '取 消',
              type: 'warning'
            }).then(() => {
                this.updatestates(row);
              this.$message({
                type: 'success',
                message: '作废成功!'
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
            });
        },

        //作废提交
        async updatestates(row) {
            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

            //后台操作：更改开票信息状态赋值给this.tablecolum
			try {
				let res = await axios.post('api/invoicefunction/updatestate',{'queryForm': this.queryForm, "record": row});
                if (res.code === 200) {
                    this.tablecolums = res.data.tablecolums;
                    this.tableData = res.data.data;
                    this.pagetotal = res.data.total;
                    this.$message.success(res.message);
                    row.invoice_status = '作废';
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('更改发票信息出错！', e.message);
			}

			// 关闭加载框
			loading.close();
        },

        //子表展开行事件触发
        async expandChange(row,expandedRows) {

            //控制只展开一行
            if (expandedRows.length) {
                this.expands = []
                if (row) {
                    this.expands.push(row.id)
                }
            } else {
                this.expands = []
            }


            this.tablecolums = [];

            if (expandedRows.length == 0) {
                return
            };

            this.getRecords(row.id);

//			this.$refs.tablecolums.doLayout();
        },

        // 查询子表方法
        async getRecords(company_id) {

            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

            //后台操作：只需要获取此公司对应的开票信息赋值给this.tablecolums
			try {
				let res = await axios.post('api/invoicefunction/columnsQuery', {"queryForm": this.queryForm, "company_id": company_id});
                if (res.code === 200) {
                    res.data.map(item =>{
                        this.tablecolums.push(item);
                    })
//                    this.tablecolums = res.data
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('查询请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();

        },

		//减票弹出框表单
		async deleteClick(row) {
		    this.dialogDeleteClick = true;

		    this.deleteclick.invoicecompany_id = row.id;
		    this.deleteclick.compname = row.compname;

            //开票限制数量
		    this.deleteclick.专票Number = row.spaecialticket_number;
		    this.deleteclick.电子专票Number = row.electronicspaecialticket_number;
		    this.deleteclick.普票Number = row.generalticket_number;
		    this.deleteclick.电子普票Number = row.electronicgeneralticket_number;

		    for (user in this.users) {
		        if (this.deleteclick.userId === this.users[user].id) {
		            this.deleteclick.billingPerson = this.users[user].username;
		        };
		    };
		    console.log(this.deleteclick)
		},

		//减票提交
		async submitDeleteClick() {

		    if (this.deleteclick.billingType == '' || this.deleteclick.billingTime == '' ||
		        this.deleteclick.number == '' || this.deleteclick.billingPerson == '') {
                this.$message({
                    message: '表单项不能有空',
                    type: 'warning'
                });
                return
            }else if (isNaN(this.deleteclick.number) || Number(this.deleteclick.number) <= 0 ||
                Number(this.deleteclick.number) > Number(this.deleteclick[this.deleteclick.billingType + 'Number'])) {
                this.$message({
                    message: '开票数量必须为数字及大于0元并且小于等于发票数量！',
                    type: 'warning'
                });
                return
            }

            //后台增加数据
            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

			try {
                console.log(this.insertclick)
				// 去搜索该公司的发票详细信息
                let res = await axios.post('api/invoicefunction/submitDeleteClick', {'queryForm': this.queryForm, 'deleteclick': this.deleteclick});
                if (res.code === 200) {
//                    this.tablecolums = []
//                    res.data.tablecolums.map(item =>{
//                        this.tablecolums.push(item);
//                    })
                    this.tableData = res.data.data;
                    this.pagetotal = res.data.total;
                    this.tablecolums = res.data.tablecolums;
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('开票出错！', e.message);
			}

			// 关闭加载框
			loading.close();

            //增添完后清空开票表单
		    this.deleteclick = {
                "invoicecompany_id":'',//公司id
                "compname":'',//公司名称
                "billingType":'',//发票类型
                "billingTime":'',//开票时间
                "number":'',//开票数量

                "billingPerson":'',//减票人
                "userId": Number(localStorage.getItem('USERID'))
            };
            this.dialogDeleteClick = false;
		},

		//减票取消
		cancelDeleteClick() {
		    //取消后清空开票表单
		    this.deleteclick = {
                "invoicecompany_id":'',//公司id
                "compname":'',//公司名称
                "billingType":'',//发票类型
                "billingTime":'',//开票时间
                "number":'',//开票数量

                "billingPerson":'',//减票人
                "userId": Number(localStorage.getItem('USERID'))
            };
            this.dialogDeleteClick = false;
		},

        //增票弹出框表单
		async insertClick(row) {
		    this.dialogInsertClick = true;

		    this.insertclick.invoicecompany_id = row.id;
		    this.insertclick.compname = row.compname;

            for (user in this.users) {
		        if (this.insertclick.userId === this.users[user].id) {
		            this.insertclick.billingPerson = this.users[user].username
		        };
		    };
            console.log(this.insertclick)
		},

		//增票提交
		async submitInsertClick() {

		    if (this.insertclick.billingType == '' ||
		        this.insertclick.number == '' || this.insertclick.money == '' || this.insertclick.billingPerson == '') {
                this.$message({
                    message: '表单项不能有空',
                    type: 'warning'
                });
                return
            }else if (isNaN(this.insertclick.number) || Number(this.insertclick.number) <= 0) {
                this.$message({
                    message: '增票数量必须为数字及大于0元！',
                    type: 'warning'
                });
                return
            }

            //后台增加数据
            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

			try {
				// 去搜索该公司的发票详细信息
                let res = await axios.post('api/invoicefunction/submitInsertClick',{'queryForm': this.queryForm, 'insertclick': this.insertclick});
                if (res.code === 200) {
                    this.tableData = res.data.data;
                    this.pagetotal = res.data.total;
                    this.tablecolums = res.data.tablecolums;
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('增票出错！', e.message);
			}

			// 关闭加载框
			loading.close();

            //增添完后清空开票表单
		    this.insertclick = {
                "invoicecompany_id":'',//公司id
                "compname":'',//公司名称
                "billingType":'',//发票类型
                "billingTime":'',//开票时间
                "number":'',//增票数量
                "billingPerson":'',//增票人
                "userId": Number(localStorage.getItem('USERID'))
            };
            this.dialogInsertClick = false;
		},

		//增票取消
		cancelInsertClick() {
		    console.log(this.insertclick);
		    //取消后清空开票表单
		    this.insertclick = {
                "invoicecompany_id":'',//公司id
                "compname":'',//公司名称
                "billingType":'',//发票类型
                "billingTime":'',//开票时间
                "number":'',//增票数量
                "billingPerson":'',//增票人
                "userId": Number(localStorage.getItem('USERID'))
            };
            this.dialogInsertClick = false;
		},

		depCopy(target, source) {
                 // 1.通过遍历拿到source中所有的属性
            for(let key in source){
                // console.log(key);

                // 2.取出当前遍历到的属性对应的取值
            let sourceValue = source[key];
                // console.log(sourceValue);

                // 3.判断当前的取值是否是引用数据类型
            if(sourceValue instanceof Object){
                    // console.log(sourceValue.constructor);
                    // console.log(new sourceValue.constructor);
                 let subTarget = new sourceValue.constructor; // 创建新的原型对象
                 target[key] = subTarget;
                 depCopy(subTarget, sourceValue);

                }else{
                    target[key] = sourceValue;
                }
            }
        },

		//编辑弹出框表单
		editClick(row) {
		    this.dialogEditClick = true;
//		    let rowcopy = new Object();
		    this.depCopy(this.updatecompany,row);
		    console.log(this.updatecompany);
//		    this.updatecompany = rowcopy;
		},

		//编辑提交
		async editClickUpdate() {

            if ( this.updatecompany.compname == '' || this.updatecompany.remake == '' || this.updatecompany.invoice_seal == ''
            || this.updatecompany.spaecialticket_quota == '' || this.updatecompany.electronicspaecialticket_quota == ''
            || this.updatecompany.generalticket_quota == '' || this.updatecompany.electronicgeneralticket_quota == ''
            || this.updatecompany.status == '' || this.updatecompany.duty_paragraph == '') {
		        this.$message({
                    message: '表单项不能有空',
                    type: 'warning'
                });
                return
            };
            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
                // 去搜索该公司的发票详细信息
                let res = await axios.post('api/invoicefunction/editClickUpdate', this.updatecompany);
                if (res.code === 200) {
                    this.query();
                    this.getCompanys();
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
			    this.query();
				this.$message.error('编辑修改出错！', e.message);
			}

			// 关闭加载框
			loading.close();

            updatecompany = {
                'id': '',
                'customer_id': '',
                'document_number':'',
                'compname': '',
                'invoice_seal': '',
                'remake': '',
                'remarks': '',
                'duty_paragraph': '',
                "spaecialticket_number":"",
                "spaecialticket_quota":"",
                "spaecialticket_is":"",
                "electronicspaecialticket_number":"",
			    "electronicspaecialticket_quota":'',
			    "electronicspaecialticket_is":'',
			    "generalticket_number":'',
			    "generalticket_quota":'',
			    "generalticket_is":'',
			    "electronicgeneralticket_number":'',
			    "electronicgeneralticket_quota":'',
			    "electronicgeneralticket_is":'',
			    "status":'',
			    "taxtype":''
            };
		    this.dialogEditClick = false;
		},

		//取消编辑
		cancelEdit() {
		    updatecompany = {
                'id': '',
                'customer_id': '',
                'document_number':'',
                'compname': '',
                'invoice_seal': '',
                'remake': '',
                'remarks': '',
                'duty_paragraph': '',
                "spaecialticket_number":"",
                "spaecialticket_quota":"",
                "spaecialticket_is":"",
                "electronicspaecialticket_number":"",
			    "electronicspaecialticket_quota":'',
			    "electronicspaecialticket_is":'',
			    "generalticket_number":'',
			    "generalticket_quota":'',
			    "generalticket_is":'',
			    "electronicgeneralticket_number":'',
			    "electronicgeneralticket_quota":'',
			    "electronicgeneralticket_is":'',
			    "status":'',
			    "taxtype":''
            };
		    this.dialogEditClick = false;
		},

		// 查询客户公司发票信息
		async query() {
		    this.expands = []
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);

			try {
				let res = await axios.post('api/invoicefunction/query', this.queryForm);
                if (res.code === 200) {
                    this.tableData = res.data.data;
                    this.pagetotal = res.data.total;
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('查询公司发票列表请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},

		//查询
        start(){
			this.queryForm.pageNo = 1
			this.queryForm.policeNumber = Number(this.queryForm.policeNumber);
			if (isNaN(this.queryForm.policeNumber) || this.queryForm.policeNumber === 0) {
			    this.queryForm.policeNumber = ''
			}

			this.query()
		},

        // 设定表格当前页
		handleCurrentPageChange (selectedPageNo) {
		  this.queryForm.pageNo = selectedPageNo
		  this.query()
		},

		// 设定每页条数
		handleSizePageChange(pagesize) {
		    this.queryForm.pagesize = pagesize;
    		this.query()
		},

        // 导入原件统计表弹出框
		async showImportDialog() {
			this.dialogimportFormVisible = true;
		},

		// 导入原件统计表
        beforeAvatarUpload(file) {
			// 显示加载框
			this.importloading = this.$loading(LOAD_STYLE);
			const isLt5M = file.size / 1024 / 1024 < 20;
			if (!isLt5M) {
				this.$message.error('上传文件大小不能超过 5MB!');
                // 关闭加载框
                this.importloading.close();
				return false;
			}
			return true;
		},

		// 导入完成
		handleAvatarSuccess(res, file, filelist) {
			try {
				if (res.code === 200) {
					this.$message.success(res.message);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('导入出错！', e.message);
			}
			// 关闭加载框
			this.importloading.close();
		},

        // 查询在职员工信息列表
        async getUsers() {
            // 显示加载框
			const loading = this.$loading(LOAD_STYLE);

			try {
				let res = await axios.post('api/invoicefunction/getUsers');
                if (res.code === 200) {
                    this.users = res.data;
                    this.$message.success(res.message);
                }else {
                    this.$message.error(res.message);
                }
			}catch (e) {
				this.$message.error('查询在职员工列表请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
        },

	},
	async mounted() {

		// 自动调整表格高度
		window.addEventListener(
          'resize',
          () =>
            (this.tableHeight = window.innerHeight - 180)
        )

        //获取主表tableData信息
        this.query();

        //查询公司名称列表
        this.getCompanys();

        //查询在职员工信息列表
        this.getUsers();

	}

});
